package com.atguigu.staservice.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.staservice.client.UcenterClient;
import com.atguigu.staservice.entity.StatisticsDaily;
import com.atguigu.staservice.mapper.StatisticsDailyMapper;
import com.atguigu.staservice.service.StatisticsDailyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-05-13
 */
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {
    @Autowired
    private UcenterClient ucenterClient;

    //统计某天注册人数
    @Override
    public void registerCount(String day) {
        //远程调用
        R countRegister = ucenterClient.countRegister(day);
        Integer count = (Integer)countRegister.getData().get("count");
        //把统计的数据添加到数据库
        StatisticsDaily staDaily=new StatisticsDaily();
        staDaily.setRegisterNum(count);//注册人数
        staDaily.setDateCalculated(day);//统计日期

        //先查询在修改
        QueryWrapper<StatisticsDaily> wrapper=new QueryWrapper<>();
        wrapper.eq("date_calculated",day);
        Integer count1 = baseMapper.selectCount(wrapper);
        if(count1>0)
            baseMapper.update(staDaily,wrapper);
        else baseMapper.insert(staDaily);
    }
    //图标显示，获取统计数据
    @Override
    public Map<String,Object> showData(String type,String begin, String end) {
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.between("date_calculated",begin,end);
        wrapper.select("date_calculated",type);//查询日期和类型
        List<StatisticsDaily> lists = baseMapper.selectList(wrapper);
        List<String> date_calculatedList=new ArrayList();
        List<Integer> numDataList=new ArrayList();
        for (StatisticsDaily daily : lists) {
            date_calculatedList.add(daily.getDateCalculated());
            if(type.equals("register_num")) {
                numDataList.add(daily.getRegisterNum());
            }
            else if(type.equals("login_num")){
                numDataList.add(daily.getLoginNum());
            }
            else if(type.equals("video_view_num")){
                numDataList.add(daily.getVideoViewNum());
            }
            else{
                numDataList.add(daily.getCourseNum());
            }
        }
        Map<String,Object> map=new HashMap<>();
        map.put("date_calculatedList",date_calculatedList);
        map.put("numDataList",numDataList);
        return map;
    }
}
